package com.zjitc.serviceedu.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoRequest;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.zjitc.common.exception.AuthException;
import com.zjitc.common.utils.RespBean;
import com.zjitc.serviceedu.entity.EduVideo;
import com.zjitc.serviceedu.mapper.EduVideoMapper;
import com.zjitc.serviceedu.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjitc.serviceedu.utils.VideoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author 赵诚挚
 * @since 2024-09-20
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Autowired
    private EduVideoMapper eduVideoMapper;
    @Override
    public boolean removeByCourseId(Long id) {
        int rows = eduVideoMapper.deleteByCourseId(id);
        return rows>0;
    }


    @Override
    public RespBean upload(MultipartFile file, EduVideo eduVideo) {


        try {
            // 上传视频到阿里云
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String title = originalFilename.substring(0, originalFilename.lastIndexOf("."));

            UploadStreamRequest request = new UploadStreamRequest(
                    VideoUtils.ACCESS_KEY_ID,
                    VideoUtils.ACCESS_KEY_SECRET,
                    title, originalFilename, inputStream);

            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);

            String videoId = response.getVideoId();
            if (!response.isSuccess()) {
                String errorMessage = "阿里云上传错误：code=" + response.getCode() + ", message=" + response.getMessage();
                if (StringUtils.isEmpty(videoId)) {
                    throw new AuthException(errorMessage);
                }
            }

            // 获取视频时长和其他元数据
            VideoUtils videoUtils = new VideoUtils();
            float duration = 0;
            int retryCount = 0;
            while (duration == 0 && retryCount < 10) {
                duration = videoUtils.getVideoDuration(videoId);
                if (duration == 0) {
                    Thread.sleep(5000);
                    retryCount++;
                }
            }
            long size = videoUtils.getVideoSize(videoId);

            // 只提取视频 ID、时长和大小
            Map<String, Object> data = new HashMap<>();
            data.put("videoId", videoId);  // 确保这里是正确的视频 ID
            data.put("duration", duration);
            data.put("size", size);
            return RespBean.success().data("data",data).msg("成功");
        } catch (IOException e) {
            throw new AuthException("文件上传失败", e);
        } catch (ClientException | InterruptedException e) {
            throw new RuntimeException("获取视频元数据失败", e);
        }
    }

    @Override
    public String getPlayURL(String playAuth, String videoId) {
        final String regionId = "cn-shanghai";  // 设置你的区域
        final String accessKeyId = VideoUtils.ACCESS_KEY_ID;  // 替换为你的AccessKeyId
        final String accessKeySecret = VideoUtils.ACCESS_KEY_SECRET;  // 替换为你的AccessKeySecret

        // 初始化客户端
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);

        try {
            // 创建请求对象
            GetPlayInfoRequest request = new GetPlayInfoRequest();
            request.setVideoId(videoId);

            // 获取响应
            GetPlayInfoResponse response = client.getAcsResponse(request);

            // 从响应中获取播放地址
            if (response.getPlayInfoList() != null && !response.getPlayInfoList().isEmpty()) {
                // 返回第一个播放地址
                return response.getPlayInfoList().get(0).getPlayURL();
            } else {
                throw new RuntimeException("未获取到播放地址");
            }
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常
            throw new RuntimeException("获取播放地址失败: " + e.getMessage());
        }
    }
}
